package com.lzw.service.impl.superAdmin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lzw.mapper.superAdmin.SuperManageMapper;
import com.lzw.pojo.SuperAdmins;
import com.lzw.service.superAdmin.SuperManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SuperManageServiceImpl implements SuperManageService {

    @Autowired
    private SuperManageMapper superManageMapper;

    @Override
    public List<SuperAdmins> list(Integer pageNum, Integer pageSize, String name, String phone) {
        PageHelper.startPage(pageNum,pageSize);
        List<SuperAdmins> list = superManageMapper.list(name,phone);
        Page<SuperAdmins> superAdmins = (Page<SuperAdmins>) list;
        return superAdmins;
    }

    @Override
    public void delete(List<Integer> ids) {
        superManageMapper.delete(ids);
    }

    @Override
    public void add(SuperAdmins superAdmins) {
        if (superManageMapper.countByName(superAdmins.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }
        if (superManageMapper.countByUsername(superAdmins.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (superManageMapper.countByPhone(superAdmins.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }
        superManageMapper.add(superAdmins);
    }

    @Override
    public void update(SuperAdmins superAdmins) {
        SuperAdmins existing = superManageMapper.getAdminById(superAdmins.getAdminId());

        //检查学生是否存在
        if (existing == null){
            throw new IllegalArgumentException("系统管理员不存在");
        }

        // 检查姓名是否修改
        if (!existing.getName().equals(superAdmins.getName())
                && superManageMapper.countByName(superAdmins.getName()) > 0) {
            throw new IllegalArgumentException("管理员姓名已存在");
        }

        // 检查用户名是否修改
        if (!existing.getUsername().equals(superAdmins.getUsername())
                && superManageMapper.countByUsername(superAdmins.getUsername()) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 检查电话是否修改
        if (!existing.getPhone().equals(superAdmins.getPhone())
                && superManageMapper.countByPhone(superAdmins.getPhone()) > 0) {
            throw new IllegalArgumentException("联系电话已存在");
        }

        superManageMapper.update(superAdmins);
    }
}
